# Importing Data
CANADA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Iraq/Canada.xlsx")

# Checking the Imported Data
View(CANADA)

# Creating Time Series Data
CANADA_ts <- ts(CANADA, start=c(2007,1), end=c(2019,03), frequency=12)

# Viewing and Checking the Created Time Series Data
CANADA_ts
sum(is.na(CANADA_ts))
library(forecast)
CANADA_ts <- tsclean(CANADA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(CANADA_ts)
plot(aggregate(CANADA_ts,FUN=mean))

# Decomposing
CANADA_ts_decomp <- decompose(CANADA_ts)
plot(CANADA_ts_decomp)

# Testing for Stationarity
acf(CANADA_ts, lag.max=20)
pacf(CANADA_ts, lag.max=20)

# To see any seasonal effect
boxplot(CANADA_ts~cycle(CANADA_ts))

# To remove trend effect
CANADA_ts_diff <- diff(CANADA_ts)
plot(CANADA_ts_diff)

# To remove variance effect
CANADA_ts_log <- log(CANADA_ts)
plot(CANADA_ts_log)

# To remove both (Trend and Variance) effects
CANADA_ts_both <- diff(log(CANADA_ts))
plot(CANADA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(CANADA_ts, lag.max=20)
acf(log(CANADA_ts), lag.max=20)
acf(diff(CANADA_ts), lag.max=20)
acf(diff(log(CANADA_ts)), lag.max=20)
pacf(CANADA_ts, lag.max=20)
pacf(log(CANADA_ts), lag.max=20)
pacf(diff(CANADA_ts), lag.max=20)
pacf(diff(log(CANADA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
CANADA_ts_model <- auto.arima(CANADA_ts)
CANADA_ts_model
CANADA_ts_model <- auto.arima(CANADA_ts, ic="aic", trace = TRUE)
CANADA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(CANADA_ts_model$resid)
acf(CANADA_ts_model$residuals, main='ACF Residual')
pacf(CANADA_ts_model$residuals, main='ACF Residual')
Box.test(CANADA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
CANADA_ts_forecast <- forecast (CANADA_ts_model, level=c(95), h=261)
plot(CANADA_ts_forecast)
CANADA_ts_forecast             


write.table(CANADA_ts_forecast, file="Canada_TSA.csv", sep=",")
